"""Middleware used by Reversion."""


import sys

import reversion
from reversion.revisions import RevisionManagementError


class RevisionMiddleware(object):
    
    """Wraps the entire request in a reversion.revision."""
    
    def process_request(self, request):
        """Starts a new reversion.revision."""
        reversion.revision.enter_revision_management()
        if request.user.is_authenticated():
            reversion.revision.user = request.user
        
    def process_exception(self, request, exception):
        """Rolls back the reversion.revision."""
        try:
            if reversion.revision.is_dirty():
                reversion.revision.rollback()
        finally:
            reversion.revision.leave_revision_management()
                
    def process_response(self, request, response):
        """Closes the reversion.revision."""
        if reversion.revision.is_managed():
            try:
                if reversion.revision.is_dirty():
                    reversion.revision.commit()
            finally:
                reversion.revision.leave_revision_management()
            if reversion.revision.is_managed():
                raise RevisionManagementError, "Unclosed revision management block at end of request."
        return response
    
    